package cn.cloud.jianghai.orderservice.feignClient;

import cn.cloud.jianghai.jianghaicommon.entity.R;
import cn.cloud.jianghai.jianghaicommon.exception.BusException;
import cn.cloud.jianghai.orderapi.entity.OrderDto;
import cn.cloud.jianghai.orderapi.feign.OrderApi;
import cn.cloud.jianghai.orderservice.query.OrderQuery;
import cn.cloud.jianghai.orderservice.service.OrderService;
import com.google.common.collect.Lists;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;

/**
 * @author Jiang.h
 * created 2022/5/21 17:36
 */
@RestController
@RequiredArgsConstructor
public class OrderFeignClient implements OrderApi {

    private final OrderService orderService;

    @Override
    public R<List<OrderDto>> findOrderList(List<Long> idList) {
        OrderQuery query = new OrderQuery();
        query.setUserIdList(idList);
        return R.success(orderService.findOrderList(query));
    }

    @Override
    public R<Boolean> insertOrder(OrderDto orderDto) {
        return R.success(orderService.insert(orderDto));
    }

    @Override
    @HystrixCommand(fallbackMethod = "fallbackHystrix", commandProperties = {
            //设置Hystrix的超时时间，默认1s
            @HystrixProperty(name="execution.isolation.thread.timeoutInMilliseconds",value = "1000"),
            //监控时间 默认5000 毫秒
            @HystrixProperty(name="circuitBreaker.sleepWindowInMilliseconds",value = "20000"),
            //失败次数。默认20次
            @HystrixProperty(name="circuitBreaker.requestVolumeThreshold",value = "5"),
            //失败率 默认50%
            @HystrixProperty(name="circuitBreaker.errorThresholdPercentage",value = "50")
    })
    public R<List<OrderDto>> testHystrix(Long id) {
        if (id == 1) {
            throw new BusException("异常");
        }
        return R.success(orderService.findOrderList(new OrderQuery()));
    }

    public R<List<OrderDto>> fallbackHystrix(Long id) {
        return R.fail("降级啦");
    }
}
